import * as React from 'react';
import { Props, State } from '../type';
import styles from './index.module.less';
import { getFileUploadUrl, getFileDownLoadUrl } from '@/utils/utils';
import { ImagePicker as AntImagePicker } from 'antd-mobile-v2';
import request from '@/services/request';
import { getToken } from '@/utils/auth';

//  const Accept = ['.jpg', '.png', '.jpeg', FILES_ACCEPTS.jpeg, FILES_ACCEPTS.png];
// const MaxSize = 5; // 单张最大5m
// const MaxLength = 9; // 最多9张

import WxImageViewer from 'react-wx-images-viewer';
export interface IFileState {
  uid: string;
  name: string;
  url?: string;
  status?: 'error' | 'success' | 'done' | 'uploading' | 'removed';
  size: number;
  type: string;
  netUid?: string;
}
export class ImagePicker extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  componentDidMount() {
    setTimeout(() => {
      this.initData();
    }, 0);
  }

  initData = () => {
    const files = this.getFileList();

    console.log(files, 'files');
    this.setState({
      files
    });
  };

  getFileList = () => {
    // const {
    //   props: { value }
    // } = this;
    const value = this.props?.formValues?.[this.props.code];
    console.log(value, '------imagevalueasfjsakfhsakfsf----');

    if (value && value.length) {
      const files: IFileState[] = value.map(
        (el: { uid: string | undefined; name: any; size: any; type: any }) => ({
          uid: el.uid,
          netUid: el.uid,
          name: el.name,
          url: getFileDownLoadUrl(el.uid),
          status: 'done',
          size: el.size,
          type: el.type
        })
      );
      return files;
    }
    return [];
  };

  validateImage = (rule: any, val2: any, callback: any) => {
    if (!this.props.required) {
      callback();
    }
    const files = this.props.form?.getFieldValue(this.props.code) || [];
    if (files.length > 0) {
      callback();
    } else {
      callback(new Error('必填项'));
    }
  };

  // 图片上传
  uploadImage = async (e: string | any[]) => {
    // let {picAddressList,imagesArray} = this.state
    const formData = new FormData();
    // console.log(e[e.length - 1]);
    const tempFile = e[e.length - 1].file;
    formData.append('file', tempFile);
    const url = getFileUploadUrl();
    const res = await request(url, {
      method: 'POST',
      data: formData,
      headers: {
        Authorization: getToken(),
        'Content-Type':
          'multipart/form-data;\',’application/x-www-form-urlencoded; charset=utf-8'
      }
    });
    console.log('res:', res);
    //fileId: "50ea2b0aebd54c23af6e7804f60600fc"
    // status: 200
    if (res.status === 200) {
      const data = res.data || {};
      console.log('tempFile---{}', tempFile);
      // fileId: "204d2c2b02284d56855dd9bfbd040e59"
      // fileName: "74254115a6934c12bd22caca6779ff19.png"
      // fileOriginName: "座位表.png"
      // filePath: ""
      // fileSize: "184"
      // fileUrl: "identity/20211026/74254115a6934c12bd22caca6779ff19.png"

      const files = [
        {
          name: data.fileOriginName,
          url: getFileDownLoadUrl(data?.fileId),
          ...tempFile,
          uid: Date.now()
        }
      ];
      this.setState({
        files
      });
    }
  };

  _onDelete = (index) => {
    const { files } = this.state;
    files.splice(index, 1);
    this.setState({
      files: [...files]
    });
  };

  onChange = (files: any, type: any, index: any) => {
    if (type == 'add') {
      this.uploadImage(files);
    }
  };

  handlePreview = async (index: number) => {
    this.setState({
      // previewImage: getFileDownLoadUrl(file.netUid),
      previewVisible: true,
      previewIndex: index
    });
  };
  handleCancel = () => this.setState({ previewVisible: false });

  render() {
    const { form, ...otherProps } = this.props;
    const { files } = this.state;

    const { previewVisible, previewIndex } = this.state;
    const {
      props: { renderMode }
    } = this;
    console.log('%c图片上传todo? 删除还没完成', 'color:red;font-weight:bold;',files);

    return (
      <div
        className={styles.imageWrap}
        style={this.props.renderMode === 'detail' ? { padding: '0' } : {}}
      >
        <span
          className={
            styles.itemTitle +
            ' ' +
            (renderMode === 'detail' ? styles.itemTitleDetail : '')
          }
        >
          {this.props.name}
        </span>
        {renderMode === 'detail' && files?.length === 0 ? (
          <div className={styles.defaultValue}>无</div>
        ) : (
          <AntImagePicker
            {...this.props}
            files={files}
            length='3'
            onChange={this.onChange}
            onImageClick={(index: any, fs: any) => {
              console.log(index, fs);
              this.handlePreview(index);
            }}
            //  selectable={files.length < 9}
            accept='image/gif,image/jpeg,image/jpg,image/png'
            disableDelete={renderMode === 'detail'}
            selectable={renderMode !== 'detail'}
          />
        )}
        {previewVisible ? (
          <WxImageViewer
            onClose={this.handleCancel}
            urls={files.map((item: any) => item.url)}
            index={previewIndex}
          />
        ) : null}
      </div>
    );
  }
}
